project(core)

# Function to find the latest Vulkan SDK version in a given directory - needed for good old Windows
function(find_latest_vulkan_sdk base_path output_var)
    file(GLOB SDK_VERSIONS "${base_path}/*")
    list(SORT SDK_VERSIONS ORDER DESCENDING)
    foreach(version IN LISTS SDK_VERSIONS)
        if(IS_DIRECTORY "${version}")
            set(${output_var} "${version}" PARENT_SCOPE)
            return()
        endif()
    endforeach()
    message(FATAL_ERROR "No Vulkan SDK version found in ${base_path}")
endfunction()

find_package(Vulkan REQUIRED)

# Source files
file(GLOB SRC_FILES 
    ${CORE_DIR}/*.hpp
    ${CORE_DIR}/*.cpp
)

add_library(core SHARED ${SRC_FILES})

# SDL & glm
target_include_directories(core PUBLIC "${SDL_DIR}/include")						   
target_link_directories(core PUBLIC "${SDL_DIR}/lib")
target_link_libraries(core PUBLIC SDL3)
target_include_directories(core PUBLIC ${GLM_DIR}/glm)

# Library linking is OS dependent
if(UNIX)
	message(STATUS "Adding Linux dependencies")
	# On linux let's override the output directory
	set_target_properties(core PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/dist")

elseif(WIN32)
	message(STATUS "Adding Windows dependencies")

	# Set the base path for Vulkan SDK
	set(VULKAN_SDK_BASE_PATH "D:/VulkanSDK")

	# Find the latest Vulkan SDK version
	find_latest_vulkan_sdk(${VULKAN_SDK_BASE_PATH} VULKAN_SDK_PATH)

	message(STATUS "Found Vulkan SDK at: ${VULKAN_SDK_PATH}")
	
    # Add Vulkan include directory
    target_include_directories(core PUBLIC "${VULKAN_SDK_PATH}/Include")
	target_link_libraries(core PRIVATE "${VULKAN_SDK_PATH}/Lib/vulkan-1.lib")
endif()

# copy dll
# Copy sdl library
add_custom_command(
		TARGET core POST_BUILD
		COMMAND ${CMAKE_COMMAND} -E copy_if_different
			"${SDL_DIR}/bin/SDL3.dll"
			$<TARGET_FILE_DIR:core>
)

# Copy shaders to the output directory
# Find all .spv files in the shaders directory
file(GLOB SHADER_SPV_FILES "${CMAKE_SOURCE_DIR}/shaders/*.spv")

# Create the shaders directory in the output directory if it doesn't exist
add_custom_command(
	TARGET core POST_BUILD
	COMMAND ${CMAKE_COMMAND} -E make_directory
		"$<TARGET_FILE_DIR:core>/shaders"
)

# Copy each .spv file to the shaders subdirectory in the output directory
foreach(SHADER_FILE ${SHADER_SPV_FILES})
	get_filename_component(FILE_NAME ${SHADER_FILE} NAME)
	add_custom_command(
		TARGET core POST_BUILD
		COMMAND ${CMAKE_COMMAND} -E copy_if_different
			"${SHADER_FILE}"
			"$<TARGET_FILE_DIR:core>/shaders/${FILE_NAME}"
	)
endforeach()